using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Dispatcher : MonoBehaviour
{
    public static Dispatcher instance;

    List<Telegram> delayTelegrams;

    void Awake()
    {
        if (null == instance)
        {
            instance       = this;
            delayTelegrams = new List<Telegram>();
        }
        else
        {
            DestroyObject(this);
        }
    }

    void Discharge(IMessager messager, Telegram telegram)
    {

    }

    public void DispatchMessage(double delay,
                                int    sender,
                                int    receiver,
                                int    msg,
                                object data)
    {
        IMessager mgrSender   = Container.instance.GetMessagerFromID(sender);
        IMessager mgrReceiver = Container.instance.GetMessagerFromID(receiver);

        if (null == mgrReceiver)
        {
            Debug.LogWarning("Warning! No Receiver with ID of " + receiver + " found");
            return;
        }

        //Telegram telegram(0.0f, sender, receiver, msg, data);
        Telegram telegram;
        telegram.dispatchTime = 0.0f;
        telegram.sender       = sender;
        telegram.receiver     = receiver;
        telegram.msg          = msg;
        telegram.data         = data;

        if (delay <= 0.0f)                                                        
        {
            Debug.Log("Instant telegram dispatched at time: " + Time.time
                    + " by " + mgrSender.ID + " for " + mgrReceiver.ID
                    + ". Msg is " + msg);

            Discharge(mgrReceiver, telegram);
        }
        else
        {
            double CurrentTime = Time.time; 

            telegram.dispatchTime = CurrentTime + delay;

            delayTelegrams.Add(telegram);  

            Debug.Log("Delayed telegram from " + mgrSender.ID + " recorded at time " 
                    + Time.time + " for " + mgrReceiver.ID
                    + ". Msg is "+ msg);
        }
    }

    void DispatchDelayedMessages()
    {
        double currentTime = Time.time;

        for (int i = delayTelegrams.Count - 1; i >= 0; i--)
        {
            Telegram telegram = delayTelegrams[i];

            if (telegram.dispatchTime > 0.0f 
                && telegram.dispatchTime < currentTime)
            {
                IMessager mgrReceiver = Container.instance.GetMessagerFromID(telegram.receiver);

                if (null != mgrReceiver)
                {
                    Discharge(mgrReceiver, telegram);
                }

                delayTelegrams.RemoveAt(i);
            }
        }
    }
}
